import { history } from '@umijs/max';
import { removeToken } from './tokenManegerUtils';
import { logout } from '@/services/auth';
import { LOGIN_PATH, REDIRECT_KEY } from '@/constants';

export async function handleLogout() {
  try {
    await logout();
  } catch (err) {
    console.error(err);
  }

  removeToken();
  const { search, pathname } = window.location;
  const urlParams = new URL(window.location.href).searchParams;
  const redirect = urlParams.get(REDIRECT_KEY);
  if (pathname !== LOGIN_PATH && !redirect) {
    history.replace({
      pathname: LOGIN_PATH,
      search: `${REDIRECT_KEY}=${pathname + search}`,
    });
  }
}

// 处理权限过期
export function handleAuthorized() {
  handleLogout();
  return Promise.reject('权限过期，请重新登录');
}
